package com.chat.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.chat.domain.converter.UserConverter;
import com.chat.domain.dto.auth.LoginDTO;
import com.chat.domain.dto.user.UserRegisterDTO;
import com.chat.domain.pojo.User;
import com.chat.excpetion.CustomException;
import com.chat.service.AuthService;
import com.chat.service.UserService;
import com.chat.util.ResultCodeEnum;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wb
 * @since 2025-06-06
 */

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserService userService;

    @Override
    public Boolean login(LoginDTO loginDTO, HttpSession session) {

        String username = loginDTO.getUsername();

        // 根据用户名称查询用户
        User user = userService.getUserByUsername(username);

        // 判断用户是否存在
        if (ObjectUtil.isEmpty(user)) {
            throw new CustomException(username + ResultCodeEnum.USERNAME_NOT_EXISTS.getMessage());
        }

        // 判断密码是否正确
        String salt = user.getSalt();
        if(!DigestUtil.md5Hex(loginDTO.getPassword() + salt).equals(user.getPassword())){
            throw new CustomException(ResultCodeEnum.PASSWORD_ERROR);
        }

        // 将用户信息保存到 session 中
        session.setAttribute("user", user);

        return true;
    }

    @Override
    public Boolean register(UserRegisterDTO userRegisterDTO) {
        String username = userRegisterDTO.getUsername();

        if (userService.getUserByUsername(username) != null) {
            throw new CustomException(username + ResultCodeEnum.USERNAME_EXISTS.getMessage());
        }

        User user = UserConverter.INSTANCE.toEntity(userRegisterDTO);
        String randomSalt = RandomUtil.randomString(12);
        user.setSalt(randomSalt);
        user.setPassword(DigestUtil.md5Hex(user.getPassword() + randomSalt));

        return userService.save(user);
    }
}
